<?php

namespace App\Libraries\Services;

use App\Libraries\Contracts\IBaseServices;
use App\Libraries\Common\ResultHelper;
use App\Libraries\Repositories\BaseRepository;
use Exception;
use Illuminate\Http\Request;

class BaseService implements IBaseServices
{
    use ResultHelper;
    /**
     * @var BaseRepository
     */
    public $repository;

    public function __construct(BaseRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * [GetAllData 获取所有数据].
     */
    public function GetAllData()
    {
        $this->pushAllCriteria();

        return $this->repository->all();
    }

    public function pushAllCriteria()
    {
    }

    public function stopSortCriteria()
    {
        $this->repository->stopSortCriteria();
    }

    /**
     * [GetDatasByCondition  根据条件查询数据].
     *
     * @param array $condition 查询条件
     * @param array $columns
     *
     * @return mixed
     */
    public function GetDatasByCondition($condition, $columns = ['*'])
    {
        return $this->repository->findWhere($condition, $columns);
    }

    /**
     * [GetCountByCondition 根据条件查询数据量].
     *
     * @param array $condition 查询条件
     *
     * @return mixed
     */
    public function GetCountByCondition($condition)
    {
        return $this->repository->findWhere($condition)->count();
    }

    /**
     * [GetById 通过编号查找对象实例].
     *
     * @param int $id 编号
     *
     * @return mixed
     */
    public function GetById($id)
    {
        return $this->repository->find($id);
    }

    /**
     * @param array $columns
     *
     * @return array|mixed
     *
     * @throws \Prettus\Repository\Exceptions\RepositoryException
     */
    public function Tree(array $columns = ['*'])
    {
        $request = request()->all();
        $lazy = isset($request['lazy']);
        $parent_name = isset($request['parent_name']) ? $request['parent_name'] : 'parent_id';
        $parent_id = isset($request['parent_id']) ? $request['parent_id'] : null;
        $query_level = isset($request['level']) ? $request['level'] : null;

        if (isset($request['columns'])) {
            $columns = array_merge(['parent_id'], explode(',', $request['columns']));
        }

        return $this->repository->children($parent_name, $parent_id, $query_level, $lazy, $columns);
    }

    /**
     * 创建新数据.
     *
     * @param array  $data
     * @param string $messages 消息模板
     *
     * @return array 消息
     */
    public function Create($data, $messages = '添加')
    {
        try {
            $model = $this->repository->model();
            $current = new $model($data);
            $data = $this->repository->SaveData($current);
            $result = $this->SuccessResult($messages.'成功', $data);
        } catch (Exception $ex) {
            $result = $this->FailResult($messages.'失败', $ex->getMessage());
        }

        return $result;
    }

    public function GetListByPage(Request $request)
    {
        $this->pushListCriteria();
        $request = $request->all();
        $limit = isset($request['limit']) ? $request['limit'] : 15;
        $data = $this->repository->paginate($limit);

        return $data;
    }

    public function pushListCriteria()
    {
    }

    /**
     * [Remove 移除操作].
     *
     * @param mixed  $condition 移除条件
     * @param bool   $isId      是否为Id
     * @param string $messages
     *
     * @return array
     */
    public function Remove($condition, $isId = false, $messages = '')
    {
        try {
            $flag = $isId ? $this->repository->delete($condition) : $this->repository->deleteWhere($condition);
            $result = $this->SuccessResult('删除成功', $flag);
        } catch (Exception $ex) {
            $result = $this->FailResult('删除失败', $ex->getMessage());
        }

        return $result;
    }

    /**
     * [ChangeStatus 修改状态].
     *
     * @param int $id 编号
     *
     * @return array
     */
    public function ChangeStatus($id)
    {
        $current = $this->repository->find($id);
        if ($current->useStatus()) {
            $message = $current->setStatus();
            try {
                $current->save();
                $result = $this->SuccessResult($message.'成功', null);
            } catch (Exception $ex) {
                $result = $this->FailResult($message.'失败', $ex->getMessage());
            }
        } else {
            $result = $this->FailResult('操作无效', '该类型不具有有效标识属性!');
        }

        return $result;
    }

    /**
     * 修改数据.
     *
     * @param array  $data     新的数据信息
     * @param int    $id       数据编号
     * @param string $messages 消息模板
     *
     * @return array 消息
     */
    public function Update($data, $id, $messages = '编辑')
    {
        try {
            $model = $this->repository->model();
            $current = new $model($data);
            $data = $this->repository->SaveData($current, $id);
            $result = $this->SuccessResult($messages.'成功', $data);
        } catch (Exception $ex) {
            $result = $this->FailResult($messages.'失败', $ex->getMessage());
        }

        return $result;
    }

    /**
     * [UniqueVerify 唯一验证].
     *
     * @param [type] $key   [键名]
     * @param [type] $value [键值]
     *
     * @return bool
     */
    public function UniqueVerify($key, $value)
    {
        return empty($this->repository->findByFild($key, $value));
    }

    /**
     * @return mixed
     *
     * @throws \Prettus\Repository\Exceptions\RepositoryException
     */
    public function GetEnableCategories()
    {
        $this->repository->pushCriteria(app('App\Criteria\StatusCriteria'));

        return $this->repository->all();
    }

    public function EditEnableOrDisable($id)
    {
        $current = $this->repository->find($id);
        if ($current->useEditEnable()) {
            $message = $current->setEditEnable();
            try {
                $data = $this->repository->update($current->toArray(), $id);
                $result = $this->SuccessResult($message.'成功', $data);
            } catch (Exception $ex) {
                $result = $this->FailResult($message.'失败', $ex->getMessage());
            }
        } else {
            $result = $this->FailResult('操作无效', '该类型不具有编辑禁用属性!');
        }

        return $result;
    }

    public function Reorder($type, $id)
    {
        $current = $this->repository->find($id);
        if ($current->useSort()) {
            $message = $current->setSort($type);
            try {
                $data = $this->repository->update($current->toArray(), $id);
                $result = $this->SuccessResult($message.'成功', $data);
            } catch (Exception $ex) {
                $result = $this->FailResult($message.'失败', $ex->getMessage());
            }
        } else {
            $result = $this->FailResult('操作无效', '该类型不具备排序属性!');
        }

        return $result;
    }

    public function EnableOrDisable($id)
    {
        $current = $this->repository->find($id);
        if ($current->useStatus()) {
            $message = $current->setStatus();
            try {
                $data = $this->repository->update($current->toArray(), $id);
                $result = $this->SuccessResult($message.'成功', $data);
            } catch (Exception $ex) {
                $result = $this->FailResult($message.'失败', $ex->getMessage());
            }
        } else {
            $result = $this->FailResult('操作无效', '该类型不具有有效标识属性!');
        }

        return $result;
    }

    /**
     * Increment a column's value by a given amount.
     *
     * @param string $column
     * @param int    $id
     * @param int    $amount
     *
     * @return mixed
     */
    public function increment($column, $id, $amount = 1)
    {
        return $this->repository->increment($column, $id, $amount);
    }

    /**
     * Decrement a column's value by a given amount.
     *
     * @param string $column
     * @param int    $id
     * @param int    $amount
     *
     * @return mixed
     */
    public function decrement($column, $id, $amount = 1)
    {
        return $this->repository->decrement($column, $id, $amount);
    }
}
